package com.ttbj.core.util;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

/**
 * spring 应用上下文工具类
 * 
 * @author Daniel
 * @date 2016年4月26日 下午7:16:06
 * 
 */
public class SpringContextUtil implements ApplicationContextAware, DisposableBean {

    private static ApplicationContext applicationContext = null;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        SpringContextUtil.applicationContext = applicationContext;
    }

    @Override
    public void destroy() throws Exception {
        SpringContextUtil.clear();
    }

    public static void clear() {
        applicationContext = null;
    }

    public static ApplicationContext getContext() {
        return applicationContext;
    }

    @SuppressWarnings("unchecked")
    public static <T> T getBean(String beanId) throws Exception {
        T t = (T) applicationContext.getBean(beanId);
        return t;
    }

    public static <T> T getBean(Class<T> cls) {
        if (applicationContext == null) {
            return null;
        }
        return applicationContext.getBean(cls);
    }

}